package com.cug.smartranch.animal.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cug.smartranch.animal.admin.common.enums.DeleteEnum;
import com.cug.smartranch.animal.admin.dao.entity.Animal;
import com.cug.smartranch.animal.admin.dao.mapper.AnimalHealthMapper;
import com.cug.smartranch.animal.admin.dao.mapper.AnimalLocationMapper;
import com.cug.smartranch.animal.admin.dao.mapper.AnimalMapper;
import com.cug.smartranch.animal.admin.dto.req.AnimalPageQueryReqDTO;
import com.cug.smartranch.animal.admin.dto.req.AnimalSaveReqDTO;
import com.cug.smartranch.animal.admin.dto.req.AnimalUpdateReqDTO;
import com.cug.smartranch.animal.admin.dto.resp.AnimalPageQueryRespDTO;
import com.cug.smartranch.animal.admin.dto.resp.AnimalQueryRespDTO;
import com.cug.smartranch.animal.admin.service.AnimalService;
import com.cug.smartranch.framework.exception.ClientException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 动物记录业务逻辑实现层
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AnimalServiceImpl extends ServiceImpl<AnimalMapper, Animal> implements AnimalService {

    private final AnimalMapper animalMapper;

    @Override
    public void createAnimal(AnimalSaveReqDTO requestParam) {
        //校验请求参数是否为空，五个请求字段都不能为空
        if(StrUtil.isEmpty(requestParam.getAnimalName())){
            throw new ClientException("动物名称不能为空");
        }
        if(ObjectUtil.isEmpty(requestParam.getAge())){
            throw new ClientException("动物年龄不能为空");
        }
        if(ObjectUtil.isEmpty(requestParam.getGender())){
            throw new ClientException("动物性别不能为空");
        }
        if(StrUtil.isEmpty(requestParam.getColor())){
            throw new ClientException("动物颜色不能为空");
        }
        if(StrUtil.isEmpty(requestParam.getSpecies())){
            throw new ClientException("动物物种不能为空");
        }

        //校验动物名称是否重复
        String animalName = requestParam.getAnimalName();
        LambdaQueryWrapper<Animal> queryWrapper = Wrappers.<Animal>lambdaQuery();
        queryWrapper.eq(Animal::getAnimalName, animalName);
        Animal isExist = animalMapper.selectOne(queryWrapper);
        if(isExist!=null){
            throw new ClientException("动物名称不能重复");
        }

        //新增animal
        Animal animal = BeanUtil.toBean(requestParam, Animal.class);
        animalMapper.insert(animal);
    }

    @Override
    public IPage<AnimalPageQueryRespDTO> selectAllAnimal(AnimalPageQueryReqDTO requestParam) {
        log.info("AnimalServiceImpl selectAllAnimal方法请求参数：{}",requestParam);
        //构建分页参数
        Page<Animal> page = new Page<>(requestParam.getPageNo(), requestParam.getPageSize());
        //构建请求参数
        LambdaQueryWrapper<Animal> queryWrapper = Wrappers.lambdaQuery(Animal.class);
        queryWrapper.like(StrUtil.isNotBlank(requestParam.getAnimalName()), Animal::getAnimalName, requestParam.getAnimalName());
        queryWrapper.ge(Objects.nonNull(requestParam.getMinAge()), Animal::getAge, requestParam.getMinAge());
        queryWrapper.le(Objects.nonNull(requestParam.getMaxAge()), Animal::getAge, requestParam.getMaxAge());
        queryWrapper.eq(Objects.nonNull(requestParam.getGender()), Animal::getGender, requestParam.getGender());
        queryWrapper.eq(Animal::getDelFlag, DeleteEnum.NORMAL.getType());
        //进行分页查询
        Page<Animal> animalPage = animalMapper.selectPage(page, queryWrapper);
        //分页结果转换：Animal转换为AnimalPageQueryRespDTO
        IPage<AnimalPageQueryRespDTO> convertPage = animalPage.convert(animal -> {
            AnimalPageQueryRespDTO responseDTO = new AnimalPageQueryRespDTO();
            BeanUtil.copyProperties(animal, responseDTO);
            return responseDTO;
        });
        return convertPage;
    }

    @Override
    public AnimalQueryRespDTO selectOne(Long id) {
        log.info("AnimalServiceImpl selectOne方法请求参数：{}",id);
        //构建查询条件
        LambdaQueryWrapper<Animal> queryWrapper = Wrappers.lambdaQuery(Animal.class);
        queryWrapper.eq(Animal::getId, id);
        queryWrapper.eq(Animal::getDelFlag, DeleteEnum.NORMAL.getType());
        //查询
        Animal animal = animalMapper.selectOne(queryWrapper);
        AnimalQueryRespDTO respDTO = BeanUtil.toBean(animal, AnimalQueryRespDTO.class);
        return respDTO;
    }

    @Override
    public void deleteOne(Long id) {
        //校验动物是否被删除过
        checkAnimalDelete(id);
        //删除动物
        LambdaUpdateWrapper<Animal> updateWrapper = Wrappers.lambdaUpdate(Animal.class);
        updateWrapper.eq(Animal::getId, id);
        Animal delAnimal = Animal.builder()
                .delFlag(DeleteEnum.DELETE.getType())
                .build();
        int update = animalMapper.update(delAnimal, updateWrapper);
        boolean flag = SqlHelper.retBool(update);
        if(!flag){
            throw new ClientException("删除动物失败，请重试！");
        }
    }

    @Override
    public void checkAnimalDelete(Long id) {
        LambdaQueryWrapper<Animal> animalQueryWrapper = Wrappers.lambdaQuery(Animal.class);
        animalQueryWrapper.eq(Animal::getId, id);
        animalQueryWrapper.eq(Animal::getDelFlag,DeleteEnum.NORMAL.getType());
        Animal animal = animalMapper.selectOne(animalQueryWrapper);
        if(Objects.isNull(animal)){
            throw new ClientException("该动物不存在或已经删除");
        }
    }

    @Override
    public void updateOne(AnimalUpdateReqDTO requestParam) {
        //基础校验
        if (Objects.isNull(requestParam)) {
            throw new ClientException("参数不能为空");
        }
        if (Objects.isNull(requestParam.getAnimalId())) {
            throw new ClientException("要修改的动物id不能为空");
        }
        //校验动物是否被删除
        checkAnimalDelete(requestParam.getAnimalId());
        //校验要修改的动物名称是否已存在，防止重名
        if(StringUtils.isNotBlank(requestParam.getAnimalName())){
            LambdaQueryWrapper<Animal> queryWrapper = Wrappers.lambdaQuery(Animal.class);
            queryWrapper.eq(Animal::getAnimalName, requestParam.getAnimalName());
            Animal animal = animalMapper.selectOne(queryWrapper);
            if(Objects.nonNull(animal)&&!Objects.equals(requestParam.getAnimalId(),animal.getId())){
                throw new ClientException("已有重名的动物，请换一个动物名称吧~~");
            }
        }
        //开始修改
        Animal animal = BeanUtil.toBean(requestParam, Animal.class);
        LambdaUpdateWrapper<Animal> updateWrapper = Wrappers.lambdaUpdate(Animal.class);
        updateWrapper.eq(Animal::getId, requestParam.getAnimalId());
        updateWrapper.eq(Animal::getDelFlag, DeleteEnum.NORMAL.getType());
        int update = animalMapper.update(animal, updateWrapper);
        boolean flag = SqlHelper.retBool(update);
        if(!flag){
            throw new ClientException("更新动物信息失败");
        }
    }

    /**
     * 获取所有动物的id集合
     * @return 所有动物的id集合
     */
    @Override
    public List<Long> selectAllAnimalIds() {
        LambdaQueryWrapper<Animal> queryWrapper = Wrappers.lambdaQuery(Animal.class);
        List<Animal> animals = animalMapper.selectList(queryWrapper);
        List<Long> ids = animals.stream().map(Animal::getId).collect(Collectors.toList());
        return ids;
    }



}
